#python 3 的 print 用法是 print () 即需要带上括号
# 字典定义时需要使用大括号{ }，列表定义时需要使用方括号[ ]，元组定义时需要使用圆括号( )
# 且元素间要用逗号 ，  隔开
'''
#多行注释可以使用
"""注释内容"""
也可以使用前后各三个连续的单引号，中间是注释内容。
单行注释可以使用 # 。
python 3 程序中的每个模块都需要缩进相同，否则会出错
'''
'''
#第一个
print ("*------------*")
people, cats, dogs = 20, 30, 15
if people < cats:
    print ("Too many cats! The world is doomed!")
if people > cats:
    print ("Not many cats! The world is saved!")
if people < dogs:
    print ("The world is drooled on!")
if people > dogs:
    print ("The world is dry!")
dogs += 5
if people >= dogs:
    print ("People are greater than or equal to dogs.")
if people <= dogs:
    print ("People are less than or equal to dogs.")
if people == dogs:
    print ("People are dogs.")

people, cars, buses = 30, 40, 15
if cars > people:
    print ("We should take the cars.")
elif cars < people:
    print ("We should not take the cars.")
# elif 与 else if 的作用相同
else:
    print ("We can't decide.")

if buses > cars:
    print ("That's too many buses.")
elif buses < cars: 
    print ("Maybe we could take the buses.")
else:
    print ("We still can't decide.")

if people > buses:
    print ("Alright,let's just take the buses.")
else:
    print ("Fine,let's stay home then.")

if (car in range(1,10)):
    print ('True')
else:
    print ('False')

the_count = [1,2,3,4,5]
# 二维列表 如：[[1,2,3,],[4,5,6]]
fruits = ['apples','oranges','pears','apricots']
change = [1,'pennies',2,'dimes',3,'quarters']
for number in the_count:
    print ("This is count %d" % number)
# for 循环开始时变量 number 就会被自动定义为第一个元素
for fruit in fruits:
    print ("A fruits of types: %s" % fruit)
for i in change:
    print ("I got %r" % i)
elements = []
for i in range(0,6):
    print ("Adding %d to the list." % i)
    elements.append(i)
# range() 函数从第一个到最后一个，但不包含最后一个数
# elements.append() 可以在列表尾部追加元需
for i in elements:
    print ("Element was: %d" % i)

print ("please input a number:")
abc = int(input(">"))
i, numbers = 0, []
while i < abc:
    print ("At the top i is %d" % i)
    numbers.append(i)
    i += 1
    print ("Numbers now: ", numbers)
    print ("At the bottom i is %d" % i)
    print ("\n")
print ("The numbers:")
for num in numbers:
    print (num)

#第二个
print ("*------------*")
from sys import exit
def gold_room():
    print ("This room is full of gold. How much do you take?")
    next = input(">")
    if "0" in next or "1" in next:
        how_much = int(next)
    else:
        dead("Man, learn to type a number.")
    if how_much < 50:
        print ("Nice, you're not greedy, you win!")
        exit(0)
    else:
        dead("You greedy bastard!")
def bear_room():
    print ("There is a bear here.")
    print ("The bear has a bunch of honey.")
    print ("The fat bear is in front of another door.")
    print ("How are you going to move the bear?")
    bear_moved = False
    while True:
        next = input(">")
        if next == "take honey":
            dead("The bear looks at you then slaps your face off.")
        elif next == "taunt bear" and not bear_moved:
            print ("The bear has mkoved from the door. You can go through it now.")
            bear_moved = True
        elif next == "taunt bear" and bear_moved:
            dead("The bear gets pissed off and chews your leg off.")
        elif next == "open door" and bear_moved:
            gold_room()
        else:
            print ("I got no idea what that means.")
def cthulhu_room():
    print ("Here you see the great evil Cthulhu.")
    print ("He, it, whatever stares at you and you go insane.")
    print ("Do you flee for your life or eat your head?")
    next = input(">")
    if "flee" in next:
        start()
    elif "head" in next:
        dead("Well that was tasty!")
    else:
        cthulhu_room()
def dead(why):
    print (why,"Good job!")
    exit(0)
def start():
    print ("You are in a dark room.")
    print ("There is a door to your right and left.")
    print ("Which one do you take?")
    next = input(">")
    if next == "left":
        bear_room()
    elif next == "right":
        cthulhu_room()
    else:
        dead("You stumble around the room until you strave.")
start()

#第三个
print ("*------------*")
ten_things = "Apple Oranges Crows Telephone Light Sugar"
print ("Wait there's not 10 things in that list, let's fix that.")
stuff = ten_things.split(' ')
#  .split(' ') 两个引号中间有空格
more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn","Banana", "Girl","Boy"]
# more_stuff 是列表
while len(stuff) != 10:
    next_one = more_stuff.pop()
    print ("Adding: ", next_one)
    stuff.append(next_one)
    print ("There's %d items now." % len(stuff))
print ("There we go: ", stuff)
print ("Let's do some things with stuff.")
print (stuff[1])
print (stuff[-1])
print (stuff.pop())
# 从列表的尾部开始弹出元素，列表需要使用方括号 [ ]
print (' '.join(stuff))
print ('#'.join(stuff[3:5]))
# ' '.join(stuff) 的作用是将元素连接起来，中间用引号间的字符隔开

states = {
    'Oregon': 'OR',
    'Florida': 'FL',
    'California':'CA',
    'New York':'NY',
    'Michigan':'MI',
    }
cities = {
    'CA':'San Francisco',
    'MI':'Detroit',
    'FL':'Jacksonville'
    }
# states与cities 是字典，字典可以通过任何东西找到与之对应的元素,需要使用大括号{ }
# 字典可以将两个毫不相干的事物关联起来
# 删除键 'Oregon'    del states['Oregon'] 
# 清空字典    states.clear()     删除字典    del states        
cities['NY'] = 'New York';cities['OR'] = 'Portland'
print ('-'*10)
print ("NY State has: ",cities['NY'])
print ("OR State has: ",cities['OR'])
print ('-'*10)
print ("Michigan's abbreviation is: ",states['Michigan'])
print ("Florida's abbreviation is: ",states['Florida'])
print ('-'*10)
print ("Michigan has: ",cities[states['Michigan']])
print ("Florida has: ",cities[states['Florida']])
print ('-'*10)
for state,abbrev in states.items():
    print ("%s is abbreviated %s" % (state,abbrev))
print ('-'*10)
for abbrev, city in cities.items():
    print ("%s has the city %s" % (abbrev,city))
print ('-'*10)
for state, abbrev in states.items():
    print ("%s state is abbreviated %s and has city %s" % (state,abbrev,cities[abbrev]))
print ('-'*10)
state = states.get('Texas',None)
if not state:
    print ("Sorry, no Texas.")
city = cities.get('TX','Does Not Exist')
print ("The city for the state 'TX' is: %s" % city)


#第四个
print ("*------------*")
def fib(n):    # 定义到 n 的斐波那契数列
    a, b = 0, 1
    while b < n:
        print(b, end=' ')
        a, b = b, a+b
    print()

def fib2(n): # 返回到 n 的斐波那契数列
    result = []
    a, b = 0, 1
    while b < n:
        result.append(b)
        a, b = b, a+b
    print(result)
    return result

fib(20);
fib2(14);

class Song:
    def _init_(self,lyrics):
        self.lyrics = lyrics
        
    def sing_me_a_song(self):
        for line in self.lyrics:
            print (line)
happy_day = Song()
bulls_on_parade = Song()#首先实例化
happy_day._init_(["Happy birthday to you",
                  "I don't wang to get sued",
                  "So I'll stop right there"])
bulls_on_parade._init_(["They rally around the famliy",
                        "With pockets full of shells"])#接着进行构造
happy_day.sing_me_a_song()
bulls_on_parade.sing_me_a_song()#最后进行访问
#python类实例化的时候不需要进行传递参数
#python中的类进行实例化的时候，需要根据构造函数确认是否除 self 之外有别的参数，
#如果有就需要进行传参
# 而且进行访问成员函数时，需要根据成员函数定义时确认是否除 self 之外有别的参数，
#如果有就需要传递参数

####################
#第五个
print ("*------------*")
import random
from urllib.request import urlopen
import sys
WORD_URL = "http://learncodethe hardway.org/words.txt"
WORDS = []
PHRASES = {
    "class %%%(%%%):":
        "Make a class named %%% that is-a %%%.",
    "class %%%(object):\n\tdef_init_(self,***)":
        "class %%% has-a _init_ that takes self and *** parameters.",
    "class %%%(object):\n\tdef ***(self,@@@)":
        "class %%% has-a function named *** that takes self and @@@ parameters.",
    "*** = %%%()":
        "Set *** to an instance of class %%%.",
    "***.***(@@@)":
        "From *** get the *** finction, and call it with parameters self, @@@.",
    "***.*** = '***'":
        "From *** get the *** attribute and set it to '***'."
    }
PHRASES_FIRST = False
if len(sys.argv) == 2 and sys.argv[1] == "english":
    PHRASES_FIRST = True
for word in urlopen(WORD_URL).readlines():
    WORDS.append(word.strip())
def convert(snippet, phrase):
    class_names = [w.capitalize() for w in random.sample(WORDS, snippet.count("%%%"))]
    other_names = random.sample(WORDS, snippet.count("%%%"))
    results = []
    param_names = []

    for i in range(0, snippet.count("@@@")):
        param_count = random.randint(1,3)
        param_names.append(', '.join(random.sample(WORDS, param_count)))

    for sentence in snippet, phrase:
        result = sentence[:]

    for word in class_names:
        result = result.replace("%%%", word, 1)

    for word in other_names:
        result = result.replace("***", word, 1)

    for word in param_names:
        result = result.replace("@@@", word, 1)

    results.append(result)
    return results
try:
    while True:
        snippets = PHRASES.keys()
        random.shuffle(snippets)
        for snippet in snippets:
            phrase = PARASES[snippet]
            question, answer = convert(snippet, phrase)
            if PHRASE_FIRST:
                question, answer = answer, question
            print (question)
            input(">")
            print ("ANSWER: %s\n\n % answer")
except EOFError:
    print ("\nBye")
####################

#第六个
print ("*------------*")
class Other(object):
    def override(self):
        print ("OTHER override()")
    def implicit(self):
        print ("OTHER implicit()")
    def altered(self):
        print ("OTHER altered()")
class Child(object):
    def _init_(self):
        self.other = Other()
    def implicit(self):
        self.other.implicit()
    def override(self):
        print ("CHILD override()")
    def altered (self):
        print ("CHILD, BEFORE OTHER altered()")
        self.other.altered()
        print ("CHILD, AGTER OTHER altered()")
son = Child()# 实例化
son._init_()# 构造
son.implicit()# 访问
son.override()
son.altered()
# 如果一个类中有 def _init_(self) 构造函数，
# 那么必须在使用该类的过程中对实例化的对象进行构造。
class Parent(object):
    def override(self):
        print ("PARENT override()")
    def implicit(self):
        print ("PARENT implicit()")
    def altered(self):
        print ("PARENT altered()")
class Child(Parent):
    def override(self):
        print ("CHILD override()")
    def altered (self):
        print ("CHILD, BEFORE OTHER altered()")
        super(Child, self).altered()
        print ("CHILD, AGTER OTHER altered()")
dad = Parent()
son = Child()
dad.implicit()
son.implicit()
dad.override()
son.override()
dad.altered()
son.altered()
'''
#第七个
print ("*------------*")



#第八个
print ("*------------*")


'''
#第九个
print ("*------------*")



#第十个
print ("*------------*")
'''

